﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace LINQToolKit.Query
{
    public sealed class PrimaryKeyComparer<T> : IEqualityComparer<T>
    {
        private string _primaryKey;
        private BindingFlags _bindingFlags;

        public PrimaryKeyComparer(string primaryKey)
            : this(primaryKey, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
        {

        }

        public PrimaryKeyComparer(string primaryKey, BindingFlags bingdingFlags)
        {
            primaryKey.AssertNull("primaryKey");
            bingdingFlags.AssertNull("bingdingFlags");

            this._primaryKey = primaryKey;
            this._bindingFlags = bingdingFlags;
        }

        public bool Equals(T x, T y)
        {
            var property = x.GetType().GetProperty(this._primaryKey, this._bindingFlags);

            if (property == null)
            {
                return false;
            }

            var xValue = property.GetValue(x, null);
            var yValue = property.GetValue(y, null);

            return xValue.Equals(yValue);
        }

        public int GetHashCode(T obj)
        {
            return obj.GetHashCode();
        }
    }
}
